<template>
  <van-popup v-model="blank" position="bottom">
    <div>
      <div class="van-picker__toolbar">
        <button type="button" class="van-picker__cancel" @click="onCancel">取消</button>
        <button type="button" class="van-picker__confirm" @click="onConfirm">确认</button>
      </div>
      <top-search v-model="search" bgcolor="#fff" @search="getList"></top-search>
      <div style="box-sizing: border-box; padding: 0.4rem;">
        <div v-if="seleList.length > 0" style="font-size: 14px;">已选中的门店：</div>
        <van-tag v-for="(item, index) in seleList" :key="index" color="#4b79f1" closeable plain 
          style="margin-right: 0.1rem;" @close="deleteSele(item)">{{ item.shopName }}</van-tag>
      </div>
      <div style="height: 40vh; overflow: auto; border-top: 1px solid #eee;">
        <radio-item v-for="item in list" :key="item.userId" :label="`${ item.shopName }(${ item.shopId })`" 
          :check="seleShopId.indexOf(item.shopId) > -1" @click.native="clickItem(item)"></radio-item>
      </div>
    </div>
    <span style="display: none;">{{ seleShopId.join(',') }}</span>
  </van-popup>
</template>

<script>
export default {
  props: {
    value: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      search: "",
      list: [],
      seleList: []
    };
  },
  methods: {
    getList() {
      if (this.search.replace(/\s/g, '') == '') {
        this.$toast('请输入搜索关键字');
        return ;
      }
      this.$store.commit('loading', true);
      this.$axios.get('/api/ShopManageController/allShop', { 
        content: this.search
      }).then(res => {
        this.$store.commit('loading');
        let list = [];
        for (let key in res) {
          list.push({ shopId: Number(key), shopName: res[key] });
        }
        this.list = list;
      });
    },
    setValue(sele) {
      this.seleList = JSON.parse(JSON.stringify(sele));
    },
    onConfirm() {
      this.blank = false;
      this.$emit('submit', this.seleList);
    },
    onCancel() {
      this.blank = false;
    },
    addSele(item) {
      let shopId = item.shopId;
      if (this.seleShopId.indexOf(shopId) < 0) {
        this.seleList.push(item);
      }
    },
    deleteSele(item) {
      let shopId = item.shopId;
      let index = this.seleShopId.indexOf(shopId);
      if (index > -1) {
        this.seleList.splice(index, 1);
      }
    },
    clickItem(item) {
      let check = this.seleShopId.indexOf(item.shopId) > -1;
      if (check) {
        this.deleteSele(item);
      } else {
        this.addSele(item);
      }
    }
  },
  computed: {
    blank: {
      get() {
        return this.value;
      },
      set(value) {
        this.$emit('input', value);
      }
    },
    seleShopId() {
      return this.seleList.map(item => item.shopId);
    }
  },
  mounted() {
  }
};
</script>
